using System;
using System.IO;
using System.Web;

namespace SoftwareMonkeys.Scriptech.Scripts
{
	public class ScriptsUtil
	{
		public ScriptsUtil ()
		{
		}
		
		static public string GetCurrentScript ()
		{
			return Scripts.GetCurrentScript(true);
		}
		
		static public string GetScriptFileName (string scriptPath)
		{
			return Path.GetFileName (scriptPath);
		}
		
		static public string GetScriptName (string scriptPath)
		{
			return Path.GetFileNameWithoutExtension (scriptPath);
		}
		
		static public string GetScriptPath (string scriptName)
		{
			return ScriptFileNamer.GetPath(scriptName);

		}
		
		static public string GetScriptContent(string scriptName)
		{
			return ScriptReader.GetContent(scriptName);
		}
		
		static public string GetShortPath (string scriptPath)
		{
			string shortPath = Path.GetFileName (scriptPath);
			
			return shortPath;
		}
		
		
		static public bool SaveScript(string originalScriptName, string newScriptName, string scriptContent)
		{
			if (IsUniqueScript(originalScriptName, newScriptName))
			{
				string originalScriptPath = GetScriptPath(originalScriptName);

				string path = GetScriptPath(newScriptName);

				if (File.Exists(originalScriptPath))
					File.Move(originalScriptPath, path);
							
				using (StreamWriter writer = File.CreateText(path))
				{
					writer.Write(scriptContent);
				}
				
				return true;
			}
			else
				return false;
		}
		
		static public bool IsUniqueScript(string originalScriptName, string newScriptName)
		{
			//string originalPath = GetScriptPath(originalScriptName);
			string newPath = GetScriptPath(newScriptName);
			
			bool editingExisting = Path.GetFileNameWithoutExtension(originalScriptName) != "untitled";

			bool nameInUse = File.Exists(newPath);
			
			// If the file name is already in use OR
			// the existing file is being edited
			if (!nameInUse || editingExisting)
			{
				return true;
			}
			else
				return false;
		}
		
		[Obsolete("Use ScriptPath.GetUrl(...) instead.")]
		static public string GetScriptUrl(string scriptName)
		{
			return ScriptPath.GetUrl(scriptName);
		}
		
		static public void DeleteScript(string scriptName)
		{
			string path = GetScriptPath(scriptName);
						
			File.Delete(path);
		}
	}
}

